package com.autonavi.abs.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * @author wwy
 * @version V1.0
 * <p>Description: Spring上下文工具</p>
 * @date 2020-07-20 15:22
 */
public class SpringContextUtils implements ApplicationContextAware {

    /**
     * spring content
     */
    private static ApplicationContext context;

    /**
     * 设置上下文环境
     *
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtils.context = applicationContext;
    }

    /**
     * 获取当前上下文
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return context;
    }

    /**
     * 根据名称获取对象
     *
     * @param name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    /**
     * 根据类型获取对象
     *
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> type) {
        return context.getBean(type);
    }

    /**
     * 根据类型获取对象map
     *
     * @param clazz
     * @param <T>
     * @return
     * @throws BeansException
     */
    public static <T> Map<String, T> getBeanMap(Class<T> clazz) throws BeansException {
        return context.getBeansOfType(clazz);
    }

}
